package com.anttribe.components.db.metadata.entity;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * 主键
 *
 * @author zhaoyong
 * @date 2021-01-04
 */
@Getter
@Setter
@ToString
public class PrimaryKey {

    /**
     * 主键名称
     */
    private String name;

    /**
     * 主键列
     */
    private List<String> columns;

    /**
     * 内部实现的主键列
     */
    private Set<PrimaryKeyColumn> innerColumns;

    public PrimaryKey() {
        columns = new ArrayList<String>();
        innerColumns = new TreeSet<PrimaryKeyColumn>(new Comparator<PrimaryKeyColumn>() {
            @Override
            public int compare(PrimaryKeyColumn o1, PrimaryKeyColumn o2) {
                return o1.getSeq() - o2.getSeq();
            }
        });
    }

    /**
     * 添加主键列
     *
     * @param columnName
     * @param seq
     */
    public void addColumn(String columnName, short seq) {
        innerColumns.add(new PrimaryKeyColumn(columnName, seq));
    }

    public List<String> getColumns() {
        if (CollectionUtils.isEmpty(columns) && !CollectionUtils.isEmpty(innerColumns)) {
            for (PrimaryKeyColumn primaryKeyColumn : innerColumns) {
                columns.add(primaryKeyColumn.getColumnName());
            }
        }
        return columns;
    }

    /**
     * 主键列
     *
     * @author zhaoyong
     * @date 2021-01-04
     */
    @Getter
    @Setter
    @ToString
    @AllArgsConstructor
    class PrimaryKeyColumn {
        /**
         * 列名
         */
        private String columnName;

        /**
         * 序列
         */
        private short seq;
    }

}
